package main

import (
	"flag"
	"fmt"
	"dooms/supplychain/blockchain"
	"dooms/supplychain/service"
	"dooms/supplychain/web"
	"dooms/supplychain/web/controller"
	"os"
	"path/filepath"
)

const (
	configPath       = "/home/snails/fabric-code/supplychain/fixtures"
	chainCodePath	 = "dooms/supplychain/chaincode/supplychaincode"
	channelID        = "supplychain-channel"
	orgName          = "Org1"
	orgAdmin         = "Admin"
	ordererOrgName   = "OrdererOrg"
	ordererID        = "orderer.example.com"
	chainCodeName    = "supplychain"
	chainCodeVersion = "1.0"
	configFile       = "config.yaml"
	userName         = "User1"
    peerOrgID 		 = "peer0.org1.example.com"
)

// GetConfigPath 配置目录
func GetConfigPath() string {
	return configPath;
}

// GetChannelConfigPath 通道配置目录
func GetChannelConfigPath() string {
	const path = "channel-artifacts"
	return filepath.Join(GetConfigPath(), path)
}

// SetEnvRootPath 设置配置文件的初始目录。
func SetEnvRootPath() {
		os.Setenv("SUPPLY_CHAINCODE_CONFIG_PATH", GetConfigPath())
}

func main() {
	port := flag.Int("p", 9000, "server port")
	role := flag.String("r", userName, "client role")
	inputChainCodeName := flag.String("cn", chainCodeName, "chaincode name")
	inputChainCodePath := flag.String("cp", chainCodePath, "chaincode path")
	flag.Parse()
	print(port, role, inputChainCodeName,inputChainCodePath )
	SetEnvRootPath()
	fSetup := blockchain.FabricSetup{
		OrdererID:        ordererID,
		ChannelID:        channelID,
		ChannelConfig:    GetChannelConfigPath() + "/channel.tx",
		ChainCodeName:    *inputChainCodeName,
		ChainCodeVersion: chainCodeVersion,
		ChaincodeGoPath:  os.Getenv("GOPATH"),
		ChaincodePath:    *inputChainCodePath,
		OrgAdmin:         orgAdmin,
		OrgName:          orgName,
		ConfigFile:       configFile,
        UserName:         *role,
        Peer0Org1ID: 	  peerOrgID,
	}

	err := fSetup.Initialize()
	if err != nil {
		fmt.Printf("Unable to initialize the Fabric SDK: %v\n", err)
		return
	}
	defer fSetup.CloseSDK()

	err = fSetup.InstallAndInstantiateCC()
	if err != nil {
		fmt.Printf("Unable to install and instantiate the chaincode: %v\n", err)
		return
	}

	serviceSetup := service.ServiceSetup {
		ChaincodeID:fSetup.ChainCodeName,
		Client:		fSetup.ClientChannel,
	}

	app := controller.Application{
		Fabric: &serviceSetup,
	}
	web.WebStart(&app, *port)
}